package com.horsen.api.gateway.filter;

import com.google.gson.JsonObject;
import com.horsen.common.util.JwtUtils;
import com.horsen.common.util.ResultCodeEnum;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 鉴权过滤器
 *
 * @author Horsen
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    /**
     * 过滤请求
     *
     * @param exchange webflux中类似HttpServlet的对象
     * @param chain    过滤器链
     * @return Mono
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获得请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获得路径
        String path = request.getURI().getPath();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        // 如果路径中含有/web/**/auth/** 说明需要鉴权
        if (antPathMatcher.match("/web/**/auth/**", path)) {
            // 获取Token
            String token = request.getHeaders().getFirst("token");
            if (token == null) {
                // 没有token 返回需要登录错误
                return out(response, ResultCodeEnum.LOGIN_AUTH);
            }
            if (!JwtUtils.checkJwtToken(token)) {
                // token不合法 返回没有权限错误
                return out(response,ResultCodeEnum.LOGIN_ACL);
            }
        }
        // 放行 使用过滤器链将请求继续向下传递
        return chain.filter(exchange);
    }

    /**
     * 定义当前过滤器优先级
     * 值越小优先级越高
     *
     * @return 优先级
     */
    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 使用webflux输入请求信息
     *
     * @param response Http响应
     * @return Mono
     */
    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        JsonObject message = new JsonObject();
        message.addProperty("success", resultCodeEnum.getSuccess());
        message.addProperty("code", resultCodeEnum.getCode());
        message.addProperty("data", "");
        message.addProperty("message", resultCodeEnum.getMessage());
        byte[] bytes = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        // 指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        // 输出http响应
        return response.writeWith(Mono.just(buffer));
    }
}
